package com.xmx.ndmallrabbitstarter.config;

import org.springframework.amqp.core.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.xmx.ndmallrabbitstarter.constants.RabbitMessageConstants.*;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2021/9/4 21:23
 */
@Configuration
@ConditionalOnProperty(name = "spring.stock.mq.enabled",matchIfMissing = false,havingValue = "true")
public class StockMqConfig {
    /*TODO TTL消息 定时*/
    public static class StockEventConfig{
        /*TODO 1.1个交换机*/
        @Bean
        public TopicExchange stockEventExchange(){
            return new TopicExchange(STOCK_EVENT_EXCHAGE,true,false);
        }
        /*TODO 2.2个队列*/
        /*2.1.普通对队列*/
        @Bean
        public Queue stockReleaseQueue(){
            return new Queue(STOCK_RELASE_QUEUE,true,false,false);
        }
        /*2.1.TTL队列*/
        @Bean
        public Queue stockLockQueue(){
            return QueueBuilder.durable(STOCK_LOCK_QUEUE).exclusive()
                    .ttl(180000) //1分钟
                    .deadLetterExchange(STOCK_EVENT_EXCHAGE)
                    .deadLetterRoutingKey(STOCK_RELEASE_DLK).build();
        }
        /*TODO 3.2个队列绑定到交换机*/
        @Bean
        public Binding stockLockQueueBinding(){
            return BindingBuilder.bind(stockLockQueue()).to(stockEventExchange()).with(STOCK_LOCK_BINDING_KEY);
        }
        @Bean
        public Binding stockReleaseBinding(){
            return BindingBuilder.bind(stockReleaseQueue()).to(stockEventExchange()).with(STOCK_RELEASE_BINDIND_KEY);
        }
        /*TODO 4.库存释放队列绑定到订单交换机*/
        @Bean
        public Binding orderCloseOtherBinding(){
            return BindingBuilder
                    .bind(stockReleaseQueue())
                    .to(new OrderMqConfig.OrderEventConfig().orderEventExchange())
                    .with(ORDER_CLOSE_OTHER_BINDIND_KEY);
        }
    }
}
